package com.xique.blelock.view.AcountManager;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.xique.MyApplication;
import com.xique.blelock.NetUtils.XqNetClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


import com.xique.blelock.Utils.MD5Util;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.VCodeType;
import com.xique.blelock.view.Home_Activity;
import com.xique.blelock.R;
import com.xique.blelock.view.Thtreepackage.CountDownButtonHelper;
import com.xique.blelock.view.Thtreepackage.ExampleClient;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterActivity extends Activity implements View.OnClickListener {

    private TextView  Mbtnsend;//返回到登录，发送验证码
//    private LinearLayout Backlogin;
    private Button Mregister;//注册
    private MyApplication app;
    private ExampleClient webSocketClient=null;
    private EditText edInput,Mgetvcode,Getpassward;
    private static String TAG = "RegisterActivity";
    public static int falgs = 0;
   public static String SENDAUTHCODE2 = "user/getVCode";

    @BindView(R.id.passwdmode)
    ToggleButton passwdmode;

   @BindView(R.id.title)
   TextView title;
    public RegisterActivity() {
        super();
    }

    @Override
    public LoaderManager getLoaderManager() {
        return super.getLoaderManager();
    }

    @Nullable
    @Override
    public View getCurrentFocus() {
        return super.getCurrentFocus();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_activity);
        ButterKnife.bind(this);
        initview();
    }

    /**
     * 初始化界面
     */
    private void initview() {
        Mbtnsend = findViewById(R.id.yanzhnema);
        edInput = findViewById(R.id.inputon);
        Mbtnsend.setOnClickListener(this);
//        Backlogin = findViewById(R.id.backers);
        Mregister = findViewById(R.id.zhucebtn);
        Mgetvcode= findViewById(R.id.getvcode);
        Getpassward = findViewById(R.id.gpassward);
        Mregister.setOnClickListener(this);

        title.setText("注册");


        Mregister.setEnabled(false);
        edInput.addTextChangedListener(textWatcher);
        Mgetvcode.addTextChangedListener(textWatcher);
        Getpassward.addTextChangedListener(textWatcher);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    public void onStateNotSaved() {
        super.onStateNotSaved();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }

    //切换密码模式
    @OnClick(R.id.passwdmode)
    public void SwitchPwdmod() {
        if(passwdmode.isChecked()){
            //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
            Getpassward.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }else{
            //选择状态 显示明文--设置为可见的密码
            Getpassward.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
    }


    /**
     * 事件监听
     * @param v
     */
    @Override
    public void onClick(View v) {
       /* app = (MyApplication) getApplication(); // 获得MyApplication对象
        webSocketClient = app.getWebSocketClient();*/
        String phonenumber = edInput.getText().toString();//获取电话号码
        if (v == Mbtnsend) {
            Pattern p = Pattern.compile("[0-9]*");
            Matcher m = p.matcher(phonenumber);
            if (m.matches()) {
                if (phonenumber.length() >= 11) {
                    XqNetClient netClient =  new XqNetClient();
                    JSONObject body1 = new JSONObject();
                    try {
                        body1.put("phone",phonenumber);
                        body1.put("mode", VCodeType.Register);
                        body1.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    netClient.sendAuthCode(body1.toString()).enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            //System.out.println("-===获取的验证码是："+ response.body());
                            Log.e(TAG, "-===获取的验证码是：" + response.body());
                            if (response.body().contains("成功")) {
                                String getdate = response.body();
                                String codes = "0";
                                try {
                                    JSONObject jsonObject = new JSONObject(getdate);
                                    //codes = jsonObject.getString("code");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                //Mgetvcode.setText(codes);
                            }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                            t.printStackTrace();
                        }
                    });
                    CountDownButtonHelper helper = new CountDownButtonHelper(Mbtnsend,
                            "发送验证码", 60, 1);
                    helper.setOnFinishListener(new CountDownButtonHelper.OnFinishListener() {

                        @Override
                        public void finish() {
                            Mbtnsend.setText("重新发送");
                        }
                    });
                    helper.start();
                    //Toast.makeText(this, "输入的是数字", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this, "输入手机号有误", Toast.LENGTH_SHORT).show();
                }

            }


        } else if (v == Mregister) {
            falgs = 2;
            String vcodes = Mgetvcode.getText().toString();//获取验证码
            String passwords = Getpassward.getText().toString();//获取密码
            XqNetClient netClient =  new XqNetClient();
            JSONObject body1 = new JSONObject();
            try {

                body1.put("loginName",phonenumber);//电话号码
                body1.put("password", MD5Util.md5(passwords));   //密码
                body1.put("vCode",vcodes);         //验证码
                body1.put("timestamp",TimeUtil.getSystemCurrentTimeLong()+"");


            } catch (JSONException e) {
                e.printStackTrace();
            }
            netClient.sendAuthCode2(body1.toString()).enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    Log.e(TAG, "-===获取注册信息：" + response.body());
                    String code = "1";
                    try {
                        JSONObject jsonObject = new JSONObject(response.body());
                        code = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (code.equals("用户名已注册")) {
                        Toast.makeText(RegisterActivity.this,"用户名已注册，请直接登录",Toast.LENGTH_SHORT).show();
                    } else if (code.equals("成功")) {
                        Intent serverIntent = new Intent(RegisterActivity.this, Home_Activity.class); // 跳主界面
                        startActivity(serverIntent);
                    }

                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }

    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

            if(edInput.getText().length()>= 6 && (Getpassward.getText().length()>=6)
                    && (Mgetvcode.getText().length()>=6)){
                Mregister.setEnabled(true);
            }else{
                Mregister.setEnabled(false);
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void afterTextChanged(Editable s) {  }
    };


}
